const getRowSpanMaps = (fields: string [], data: Array<any>): any => {
  if (data.length < 2) return null
  const rowSpanMaps: any = {}
  fields.forEach((field:any, index:number) => {
    let startIndex = 0
    let endIndex = 1
    let sameCount = 1
    let leftPoint = 0
    const leftMap = rowSpanMaps[fields[index - 1]]
    const cache = new Map()
    if (!index) leftPoint = Infinity
    while (endIndex <= data.length) {
      // 根据左侧map来限制右侧map
      if (index) {
        // 获取左侧列的位置指针
        leftPoint = (leftMap.get(endIndex - 1) + endIndex - 1) || leftPoint
      }
      // 有值且重复，结束指针小于左侧列指针时，相同个数加一
      if (data[endIndex]
        && data[endIndex][field]
        && data[startIndex][field] === data[endIndex][field]
        && endIndex < leftPoint) {
        // 相同个数加一
        sameCount++
      } else {
        // 纪录相同个数
        if (sameCount > 1) cache.set(startIndex, sameCount)
        // 重置相同个数计数
        sameCount = 1
        // 开始下标移动到 上一轮结束下标
        startIndex = endIndex
      }
      // 结束指针后移
      endIndex++
    }
    rowSpanMaps[field] = cache
  })
  return rowSpanMaps
}

export const newTableRowSpan = (table:any, fields:string[]):any => {
  const rowSpanMaps = getRowSpanMaps(fields, table)
  return (params:any) => {
    if (table.length < 2) return null
    if (fields.includes(params.colDef.field)) {
      /** 将当前的合并行数传入data中， 在 cellRenderer 中进行添加margin 用于垂直居中 */
      params.data.rowSpanNum = rowSpanMaps[params.colDef.field].get(params.node.rowIndex) || 1
      return rowSpanMaps[params.colDef.field].get(params.node.rowIndex) || 1
    }
    return 1
  }
}